/**
 * 用户认证模块 - 提供通用的用户登录状态管理功能
 */
const AuthService = {
    // 获取用户信息
    getUserInfo() {
        return {
            token: localStorage.getItem('token'),
            username: localStorage.getItem('username'),
            userId: localStorage.getItem('userId'),
            userData: JSON.parse(localStorage.getItem('userData'))
        };
    },

    // 检查用户是否已登录
    isLoggedIn() {
        const { token, username } = this.getUserInfo();
        return !!(token && username);
    },

    // 保存用户登录信息
    saveUserInfo(userData) {
        if (!userData) return false;
        
        localStorage.setItem('token', 'Bearer ' + userData.token);
        localStorage.setItem('username', userData.username);
        localStorage.setItem('userId', userData.id);
        localStorage.setItem('userData', JSON.stringify(userData));
        return true;
    },

    // 清除用户登录信息
    clearUserInfo() {
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        localStorage.removeItem('userId');
        localStorage.removeItem('userData');
    },

    // 用户登录
    login(username, password) {
        return new Promise((resolve, reject) => {
            if (!window.ApiService) {
                reject(new Error('ApiService未定义'));
                return;
            }

            ApiService.user.login(username, password)
                .then(response => {
                    if (response.data) {
                        this.saveUserInfo(response.data);
                        resolve(response.data);
                    } else {
                        reject(new Error('登录失败，未返回用户数据'));
                    }
                })
                .catch(error => {
                    console.error("登录失败:", error);
                    layer.msg(error.response.data || '登录失败')
                    reject(error);
                });
        });
    },

    // 用户退出登录
    logout() {
        this.clearUserInfo();
        window.location.reload();
    },

    // 检查登录状态并执行回调
    checkLoginBeforeAction(callback, redirectUrl) {
        if (this.isLoggedIn()) {
            if (typeof callback === 'function') {
                callback();
            }
            return true;
        } else {
            // 如果提供了重定向URL，则跳转
            if (redirectUrl) {
                window.location.href = redirectUrl;
                return false;
            }
            
            // 尝试显示登录模态框
            this.showLoginModal();
            return false;
        }
    },

    // 显示登录模态框
    showLoginModal() {
        const mask = document.getElementById('mask');
        if (mask) {
            mask.style.display = 'flex';
        } else {
            alert('请先登录');
            window.location.href = './login.html';
        }
    },

    // 更新UI显示用户信息
    updateLoginUI() {
        const loginStatusElement = document.getElementById('loginStatus');
        if (!loginStatusElement) return;

        if (this.isLoggedIn()) {
            const { username } = this.getUserInfo();
            loginStatusElement.innerHTML = `欢迎，<span class="username">${username}</span> | <a href="javascript:;" id="logoutBtn">退出</a>`;
            
            // 添加退出登录事件
            const logoutBtn = document.getElementById('logoutBtn');
            if (logoutBtn) {
                logoutBtn.addEventListener('click', () => this.logout());
            }
        } else {
            loginStatusElement.innerHTML = '请<a class="login" href="./register.html">注册</a>/<a class="login" href="./login.html">登录</a>账号';
        }
    },

    // 初始化购物车数量显示
    updateCartCount() {
        if (!this.isLoggedIn() || !window.ApiService) return;
        
        const cartCountElement = document.getElementById('cartCount');
        if (!cartCountElement) return;
        
        ApiService.cart.getCart()
            .then(response => {
                const cartItems = response.data || [];
                const count = cartItems.length;
                cartCountElement.textContent = count;
            })
            .catch(error => {
                console.error('获取购物车失败:', error);
            });
    }
};

// 导出到全局，使其在所有JS文件中可用
window.AuthService = AuthService;